//
//  CameraViewController.m
//  HaiKangDemo
//
//  Created by 崔 on 16/9/30.
//  Copyright © 2016年 崔. All rights reserved.
//

#import "CameraViewController.h"
#import "GlobalKit.h"
#import "EZOpenSDK.h"
#import "EZAccessToken.h"
#import "EZCameraInfo.h"
#import "CameraListCell.h"
#import <MJRefresh.h>
#import "EZLivePlayViewController.h"
#import "EZLivePlayViewController.h"
#import "LGControllerManager.h"
#import "doorViewController.h"
#import "doorsTableViewController.h"
#import "relevanceInfo.h"
#import "BaseViewController.h"
#import "headerView.h"
#import "CHYCameraDoorInfo.h"
#import "ALSHeader.h"
#define CHYRELEVANCEINFONOTS @"CHYrelevanceInfoNots"

//沙盒
#define CHYCAMERALISTPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"cameraList.plist"]

static NSString * const JPHeaderId = @"header";

@interface CameraViewController () <CameraListCellDelegate>

/**摄像头数组*/
@property (nonatomic ,strong) NSMutableArray *CameraLists;

@property (nonatomic,assign) NSInteger currentPageIndex;


/*关联的门信息*/
@property (nonatomic,strong)relevanceInfo *relevanceInfo;

//操作的索引
@property (nonatomic ,assign)NSInteger operationIndex;

@end

@implementation CameraViewController

static  NSString *cameraListID = @"cameraListID";


- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self setNav];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    [self loginHaiKangSever];
   
//    [self setUpFooterRefresh];
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CameraListCell class]) bundle:nil] forCellReuseIdentifier:cameraListID];
    
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name: CHYRELEVANCEINFONOTS object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNav];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self loginHaiKangSever];

    // 判断是否过期
    if ([self isServiceExpiration]) { //过期了

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录服务器" message:@"系统检测到您之前登录的信息已过期,请重新登录.如选否,则您有可能无法进行视频预览" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *OK = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            

            [EZOpenSDK openLoginPage:^(EZAccessToken *accessToken) {
                
                //accessToken 登录凭证
                [[GlobalKit shareKit] setAccessToken:accessToken.accessToken];
                
                [EZOpenSDK setAccessToken:accessToken.accessToken];
                
                //保存服务器登录过期时间
                [self saveExpirationTime:accessToken];
                
            }];
            
        }];
        
        UIAlertAction *canle = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:OK];
        
        [alert addAction:canle];
        
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
//    NSLog(@"还未过期");
    
}
//接受通知
- (void)notificationAction:(NSNotification *)notification{
    
    NSMutableArray *tempArr = self.CameraLists;
    
    CHYCameraDoorInfo *info = tempArr[self.operationIndex];
    
    info.relInfo = notification.object;
    
    self.CameraLists = tempArr;
    //写入沙盒
    [NSKeyedArchiver archiveRootObject:self.CameraLists toFile:CHYCAMERALISTPath];
    
    [self.tableView reloadData];
    
}
#pragma mark - 设置导航
- (void)setNav{

    if (self.parentViewController) {

        UIViewController *vc = self.parentViewController;
        
        vc.navigationItem.title = @"阿里桑智能门禁";
        
        UIButton *left = [ALSBarButton backButtonWithTitle:@"主页"];
        
        [left addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:(UIControlEventTouchUpInside)];
        
        vc.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:left];
        
        UIButton *right = [ALSBarButton normalButtonWithNormalTitle:@"注销" selectedTitle:@"注销" highlightTitle:@"注销"];
        [right addTarget:self action:@selector(canleClick) forControlEvents:(UIControlEventTouchUpInside)];
        
        vc.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:right];
    }
}

////左边的返回按钮
//- (void)leftBtnClick{
//    [self.navigationController popViewControllerAnimated:YES];
//}

//注销按钮
- (void)canleClick{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注销摄像头" message:@"您真的要注销摄像头登录吗?注销后下次进入此界面时需要再次登录" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *OK = [UIAlertAction actionWithTitle:@"注销" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [[GlobalKit shareKit] clearSession];
    }];
    
    UIAlertAction *canle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:OK];
    
    [alert addAction:canle];
    
    [self presentViewController:alert animated:YES completion:nil];
 

}

/**
 登录服务器
 */
- (void)loginHaiKangSever{
    
    if ([GlobalKit shareKit].accessToken)
    {
        [EZOpenSDK setAccessToken:[GlobalKit shareKit].accessToken];
        
    
        //获取数据
        [self addRefreshKit];
}
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录服务器" message:@"系统检测到你从未登录过海康服务器,如选否,您可能无法连接摄像头" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *OK = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [EZOpenSDK openLoginPage:^(EZAccessToken *accessToken) {
                
                //accessToken 登录凭证
                [[GlobalKit shareKit] setAccessToken:accessToken.accessToken];
                
                [EZOpenSDK setAccessToken:accessToken.accessToken];
                
                //保存服务器登录过期时间
                [self saveExpirationTime:accessToken];
                
                [self addRefreshKit];
                
            }];
            
            [self.tableView reloadData];
            return;
            
        }];
        
        UIAlertAction *canle = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil];
        
        [alert addAction:OK];
        
        [alert addAction:canle];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}

//保存过期时间

- (void)saveExpirationTime:(EZAccessToken *)accessToken{
    
    //过期秒数
     NSInteger s = accessToken.expire;
    
    // 过期时间
    NSDate *expireDate = [NSDate dateWithTimeIntervalSinceNow:s];
    
    // 设置系统时区为本地时区
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    
    // 计算本地时区与 GMT 时区的时间差
    NSInteger interval = [zone secondsFromGMT];
    
    // 在 GMT 时间基础上追加时间差值，得到本地时间
    expireDate = [expireDate dateByAddingTimeInterval:interval];
    
    //    NSLog(@"----%@",date);
    
        [[NSUserDefaults standardUserDefaults] setObject:expireDate forKey:@"expireDate"];
    
        [[NSUserDefaults standardUserDefaults] synchronize];

    
}
//判断登录是否过期(YES过期)
- (BOOL)isServiceExpiration{
    
    
    NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:@"expireDate"];
    
    NSDate *nowDate = [NSDate date];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    
    // 计算本地时区与 GMT 时区的时间差
    NSInteger interval = [zone secondsFromGMT];
    
    // 在 GMT 时间基础上追加时间差值，得到本地时间
    nowDate = [nowDate dateByAddingTimeInterval:interval];
    
    //当前时间和date比较,返回早的时间.
    NSDate *date1 = [nowDate earlierDate:date];
    
//    NSLog(@"当前时间 %@",nowDate);
    
//    NSLog(@"存的时间 %@",date);
    
//    NSLog(@"比较出来的%@",date1);

    //如果返回的时间和存入的时间相同 或者 当前的时候和存入的时间相同 则表明过期了
    if ([date1 isEqualToDate:date] || [nowDate isEqualToDate:date]) {
        
        return YES;
        
    }
    
    return NO;
    
}

//懒加载
- (NSMutableArray *)CameraLists{
    
    if (_CameraLists == nil) {
        
        //先从沙盒里面取
        _CameraLists = [NSKeyedUnarchiver unarchiveObjectWithFile:CHYCAMERALISTPath];
        
//        _CameraLists = [NSMutableArray array];

        
        if (_CameraLists == nil) {
            
            _CameraLists = [NSMutableArray array];
        }
        
    }
    
    return _CameraLists;
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.CameraLists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CameraListCell *cell = [tableView dequeueReusableCellWithIdentifier:cameraListID];
    
    cell.tag = indexPath.row;
    
    CHYCameraDoorInfo *info = self.CameraLists[indexPath.row];
    
    cell.relevanceInfo = info.relInfo;
    
    cell.cameraInfo = info.cameraInfo;
    
    cell.delegate = self;
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [self performSegueWithIdentifier:@"goToPlay" sender:nil];
    
}

//跳转到视频预览界面
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    
    NSInteger index = [self.tableView indexPathForSelectedRow].row;
    
    //拿到目标控制器
    EZLivePlayViewController *goalVC = segue.destinationViewController;
    
    //更改模型为CHYCameraDoorInfo
    CHYCameraDoorInfo *info =  self.CameraLists [index] ;
    
    EZCameraInfo *ezInfo = info.cameraInfo;
    
    goalVC.cameraId = ezInfo.cameraId;
    
    goalVC.cameraName = ezInfo.cameraName;
    
    goalVC.deviceSerial = ezInfo.deviceSerial;
    
    goalVC.relevanceInfo = info.relInfo;
    
    goalVC.isOnline = ezInfo.isOnline;
    
}

- (void)addRefreshKit{
    
    self.currentPageIndex = 0;
    
//    [self.tableView.mj_header beginRefreshing];
    
    __weak typeof(self)weakSelf = self;
    
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    
    [EZOpenSDK getCameraList:weakSelf.currentPageIndex++ pageSize:10 completion:^(NSArray *cameraList, NSError *error) {
        
        NSMutableArray *arr = [NSMutableArray array];
        
        //取沙盒里面的数据
        NSArray *cameraInfos = [NSKeyedUnarchiver unarchiveObjectWithFile:CHYCAMERALISTPath];
        
        //序列号
        NSString *deviceSerial;
        
        //遍历取出来的数据
        for (CHYCameraDoorInfo *info in cameraInfos) {
            
            EZCameraInfo *cinfo = info.cameraInfo;
            
            //取出序列号
            deviceSerial = cinfo.deviceSerial;
        }
    
        
            if (!error) {
                
                for (EZCameraInfo *cInfo in cameraList) {
                    
                    //判断沙盒里面是否有这个序列号
                    if ([cInfo.deviceSerial isEqualToString:deviceSerial]) {
                        
                        return ;
                    }
                    
                    CHYCameraDoorInfo *cdInfo = [[CHYCameraDoorInfo alloc] init];
                    
                    cdInfo.cameraInfo = cInfo;
                    
                    [arr addObject:cdInfo];
                }
                
                [weakSelf.CameraLists addObjectsFromArray:arr];
                
            //写入沙盒
            [NSKeyedArchiver archiveRootObject:self.CameraLists toFile:CHYCAMERALISTPath];
                
//                NSLog(@"添加到沙盒成功");
                //在主线程上刷新数据
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [weakSelf.tableView reloadData];
                    
                });
            
            } else{
                
//                CHYLog(@"%ld",(long)error.code);
            }
        
    }];
}

//设置上拉刷新

- (void)setUpFooterRefresh{

    
//    __weak typeof(self)weakSelf = self;
//
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//    
//        [EZOpenSDK getCameraList:self.currentPageIndex++
//                        pageSize:10
//                      completion:^(NSArray *cameraList, NSError *error) {
//                          if(cameraList.count == 0)
//                          {
//                              weakSelf.tableView.mj_footer.hidden = YES;
//                              return;
//                          }
//                          [weakSelf.CameraLists addObjectsFromArray:cameraList];
//                          
//                          
//                          //写入沙盒
//                          [NSKeyedArchiver archiveRootObject:self.CameraLists toFile:CHYCAMERALISTPath];
//                          
//                          [weakSelf.tableView reloadData];
//                          [weakSelf.tableView.mj_footer endRefreshing];
//                      }];
//        
//        
//    }];

}

#pragma mark - CameraListCellDelegate

- (void)CameraListCell:(CameraListCell *)CameraListCell withControllers:(NSArray *)controllers andBtnIndex:(NSInteger)index{
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"doosTableViewController" bundle:nil];
    
    
    doorViewController *vc = [sb instantiateInitialViewController];


    vc.controllers = controllers;
    self.operationIndex = index;
    
    BaseViewController *nav = [[BaseViewController alloc] initWithRootViewController:vc];

    
    [self presentViewController:nav animated:YES completion:nil];

    
    return;
//    doorsTableViewController *doorsVC = [sb instantiateInitialViewController];
//    
//    doorsVC.controllers = controllers;
//    
//    self.operationIndex = index;
//    
//    BaseViewController *nav = [[BaseViewController alloc] initWithRootViewController:doorsVC];
//    
//    [self presentViewController:nav animated:YES completion:nil];
    
    
}

@end
